from auth_decorator import login_required,permission_required
from flask import Blueprint,  request, jsonify,render_template,session
from models import UserModel
from flask_jwt_extended import jwt_required
from flask_jwt_extended import create_access_token
blueprint = Blueprint('/', __name__, url_prefix='/')


@blueprint.route("/", methods=['GET', 'POST'])
def index():
    return render_template('index.html')



# 登录
@blueprint.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return { 'message': '非法请求'}
    else:
        # 验证用户名密码
        # 验证成功后，将用户id和权限信息存入session
        # 验证失败，返回错误信息
    
        data = request.get_json()
        print(data['username'])
        user = UserModel.query.filter(UserModel.username == data['username']).first()
        session['_user_id'] = user.id
        session['_user_username'] = user.username
        session['permission'] = ':'.join([power.code for role in user.role for power in role.power])
        access_token = create_access_token(identity= session['_user_id'])
        print(session['permission'])
        print(session['_user_id'])

        return {'status': 'success',  'message': '登录成功','access_token': access_token}
    
# 退出
@blueprint.route("/logout", methods=['GET', 'POST'])
def logout():
    session['_user_id'] = 0
    session['permission'] = 0
    session['_user_username'] = '未登录'
    return {'status': 'success',  'message': '退出成功'}
# 管理员后台
@blueprint.route('/admin', methods=['GET', 'POST'])
@login_required
@jwt_required()
@permission_required('write')
def admin():
    return {'status': 'success',  'message': '登录管理员成功'}           